package com.gxnu.edu.cn.client.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxnu.edu.cn.ttxxt.entity.Friendship;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
public class FriendClient {
    @Autowired
    private RestTemplate restTemplate;
    private String baseUrl = "http://localhost:8080";

    public FriendClient() {
        // 配置RestTemplate使用Jackson消息转换器
        restTemplate = createConfiguredRestTemplate();
    }

    private RestTemplate createConfiguredRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 添加Jackson消息转换器
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(new ObjectMapper());
        restTemplate.getMessageConverters().add(converter);
        return restTemplate;
    }

    public CompletableFuture<List<Friendship>> getFriends(Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 使用ParameterizedTypeReference指定返回类型
                ResponseEntity<List<Friendship>> response = restTemplate.exchange(
                        baseUrl + "/api/friends/list?userId=" + userId,
                        HttpMethod.GET,
                        null,
                        new ParameterizedTypeReference<List<Friendship>>() {}
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("获取好友列表失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> sendFriendRequest(Map<String, Object> request) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/friends/requests",
                        request,
                        Map.class
                );
                System.out.println(response.getBody());
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("发送好友请求失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> acceptFriendRequest(Long requestId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/friends/requests/" + requestId + "/accept",
                        null,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("接受好友请求失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> rejectFriendRequest(Long requestId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/friends/requests/" + requestId + "/reject",
                        null,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("拒绝好友请求失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> deleteFriend(Long friendId, Long userId) {
        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求体
        Map<String, Object> requestBody = Map.of("userId", userId);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        return CompletableFuture.supplyAsync(() -> {
            try {
                // 发送带请求体的DELETE请求
                ResponseEntity<Map> response = restTemplate.exchange(
                        baseUrl + "/api/friends/" + friendId,
                        HttpMethod.DELETE,
                        requestEntity, // 设置请求体
                        Map.class
                );

                if (response.getStatusCode().is2xxSuccessful()) {
                    return response.getBody();
                } else {
                    throw new RuntimeException("删除好友失败，状态码: " + response.getStatusCode());
                }
            } catch (Exception e) {
                throw new RuntimeException("删除好友失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> updateFriendRemark(Long friendId, String remark) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Map<String, String> request = Map.of("remark", remark);
                ResponseEntity<Map> response = restTemplate.exchange(
                        baseUrl + "/api/friends/" + friendId + "/remark",
                        org.springframework.http.HttpMethod.PUT,
                        new org.springframework.http.HttpEntity<>(request),
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("更新好友备注失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> updateFriendGroup(Long friendId, String groupName) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Map<String, String> request = Map.of("groupName", groupName);
                ResponseEntity<Map> response = restTemplate.exchange(
                        baseUrl + "/api/friends/" + friendId + "/group",
                        org.springframework.http.HttpMethod.PUT,
                        new org.springframework.http.HttpEntity<>(request),
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("更新好友分组失败: " + e.getMessage(), e);
            }
        });
    }
}